﻿using System;
using System.Collections;
using System.Collections.Generic;
using Flagwind.Services;
using Flagwind.Resources;
using Flagwind.Runtime.Serialization;

namespace Flagwind.Collections.Commands
{
	[CommandOption("count", Type = typeof(int), DefaultValue = 1, Description = "${Text.QueueCommand.Options.Count}")]
	[CommandOption("round", Type = typeof(int), DefaultValue = 1, Description = "${Text.QueueCommand.Options.Round}")]
	[CommandOption("queues", Type = typeof(string), Description = "${Text.QueueCommand.Options.Queues}")]
	public class QueueOutCommand : CommandBase<CommandContext>
	{
		#region 构造方法

		public QueueOutCommand() : this("Out")
		{
		}

		public QueueOutCommand(string name) : base(name)
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(CommandContext context)
		{
			var count = context.Expression.Options.GetValue<int>("count");
			int round = context.Expression.Options.GetValue<int>("round");
			var result = new List<object>(count);

			if(count < 1)
			{
				throw new CommandOptionValueException("count", count);
			}

			if(round < 1)
			{
				throw new CommandOptionValueException("round", round);
			}

			var queues = QueueCommandHelper.GetQueues(context.CommandNode, context.Expression.Options.GetValue<string>("queues"));

			foreach(var queue in queues)
			{
				if(queue.Count == 0)
				{
					context.Output.WriteLine(CommandOutletColor.DarkRed, ResourceUtility.GetString("Text.QueueIsEmpty", queue.Name));
					continue;
				}

				for(int i = 0; i < round; i++)
				{
					var items = queue.Dequeue(count);

					if(items == null)
					{
						break;
					}

					foreach(var item in items)
					{
						result.Add(item);
					}

					context.Output.WriteLine(Serializer.Text.Serialize(items));
					context.Output.WriteLine(CommandOutletColor.DarkGreen, string.Format(ResourceUtility.GetString("Text.QueueOutCommand.Message", i + 1, count, queue.Name)));
				}
			}

			return result.ToArray();
		}

		#endregion
	}
}